package com.seven.good.service.impl;

import com.seven.good.dao.BidRecordMapper;
import com.seven.good.dao.GoodMapper;
import com.seven.good.exception.AuctionException;
import com.seven.good.pojo.BidRecord;
import com.seven.good.service.AuctionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CachePut;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class AuctionServiceImpl implements AuctionService {

    @Autowired
    BidRecordMapper bidRecordMapper;

    @Autowired
    GoodMapper goodMapper;

    @Override
    @CachePut(value="bidroom",key = "#bidRecord.gid")
    public BidRecord doRecordInBidroom(BidRecord bidRecord) {
        // 插入数据库记录
        try {
            bidRecord.setBidTime(new Date());
            bidRecord.setBidState("落后");
            bidRecordMapper.insertSelective(bidRecord);
            return bidRecord;
        } catch (Exception e) {
            throw new AuctionException("竞价室插入数据失败");
        }
    }

    @Override
    public List<BidRecord> listRecordListById(Integer gid) {
        try {
            return bidRecordMapper.listRecordListById(gid);
        } catch (Exception e) {
            throw new AuctionException("竞价室列表数据获取出现错误");
        }
    }

    @Override
    public List<BidRecord> listAllRecordByGid(Integer gid) {
        try {
            return bidRecordMapper.listAllRecordByGid(gid);
        } catch (Exception e) {
            throw new AuctionException("获取竞拍列表异常");
        }
    }

    @Override
    public BidRecord getNewRecordById(Integer gid) {
        try {
            return bidRecordMapper.getLatestRecord(gid);
        } catch (Exception e) {
            throw new AuctionException("获取最新竞拍记录异常");
        }
    }

    @Override
    public void updateGoodState(Integer gid,Integer code) {
        try {
            bidRecordMapper.updateGoodState(gid,code);
        } catch (Exception e) {
            throw new AuctionException("更改商品状态码异常");
        }
    }

    @Override
    public boolean cancleBid(Integer gid) {
        try {
            if(goodMapper.deleteByGid(gid)>0){
                return true;
            }
            return false;
        } catch (Exception e) {
            throw new AuctionException("数据库软删除异常");
        }
    }

    @Override
    public void updateDealPrice(int gid,String price) {
        try {
            goodMapper.updateDealPrice(gid,new BigDecimal(price));
        } catch (Exception e) {
            throw new AuctionException("数据库更新成交价出错");
        }
    }

    @Override
    public int getPublisherIdByGid(Integer gid) {
        try {
            return goodMapper.getPublisherIdByGid(gid);
        } catch (Exception e) {
            throw new AuctionException("获取发布人ID出错");
        }
    }
}
